import 'package:permission_handler/permission_handler.dart';

class PermissionManager {
  static Future<bool> requestCameraPermission() async {
    try {
      // 检查相机权限状态
      PermissionStatus status = await Permission.camera.status;
      
      if (status.isGranted) {
        return true;
      }
      
      // 如果权限被永久拒绝，返回false
      if (status.isPermanentlyDenied) {
        // 可以在这里提示用户去设置页面开启权限
        return false;
      }

      // 请求相机权限
      status = await Permission.camera.request();
      
      // 等待一小段时间确保Activity完全初始化
      await Future.delayed(const Duration(milliseconds: 100));
      
      return status.isGranted;
    } catch (e) {
      print('Camera permission request error: $e');
      // 如果出现异常，等待后重试一次
      await Future.delayed(const Duration(milliseconds: 500));
      try {
        final status = await Permission.camera.request();
        return status.isGranted;
      } catch (retryError) {
        print('Camera permission retry error: $retryError');
        return false;
      }
    }
  }
} 